# -*- coding: utf-8 -*-

import copy

global_env = copy.copy(globals())

def index():

    record = db( ( db.kioskContribution.approved == False ) &
                 ( db.kioskContribution.processed == False ) ).select().first()
 
    if( 'firstName' in request.vars ):

        record.update_record( firstName = request.vars.firstName,
                              hometown = request.vars.hometown,
                              age = request.vars.age,
                              question = request.vars.question,
                              contribution = request.vars.contribution,
                              processed = request.vars.processed,
                              approved = request.vars.approved )

        response.flash = DIV( 'record updated' )
    
        record = db( ( db.kioskContribution.approved == False ) &
                     ( db.kioskContribution.processed == False ) ).select().first()

    form = SQLFORM( db.kioskContribution, record, deletable=False, ignore_rw=True and not hasattr( db.kioskContribution, '_primary_key') )

    return dict( form=form, table=db.kioskContribution )

# ##########################################################
# ## auxiliary functions
# ###########################################################


def get_databases(request):
    dbs = {}
    for (key, value) in global_env.items():
        cond = False
        try:
            cond = isinstance(value, GQLDB)
        except:
            cond = isinstance(value, SQLDB)
        if cond:
            dbs[key] = value
    return dbs


databases = get_databases(None)


def eval_in_global_env(text):
    exec ('_ret=%s' % text, {}, global_env)
    return global_env['_ret']


def get_database(request):
    if request.args and request.args[0] in databases:
        return eval_in_global_env(request.args[0])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))


def get_table(request):
    db = get_database(request)
    if len(request.args) > 1 and request.args[1] in db.tables:
        return (db, request.args[1])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))


def get_query(request):
    try:
        return eval_in_global_env(request.vars.query)
    except Exception:
        return None


def query_by_table_type(tablename,db,request=request):
    keyed = hasattr(db[tablename],'_primarykey')
    if keyed:
        firstkey = db[tablename][db[tablename]._primarykey[0]]
        cond = '>0'
        if firstkey.type in ['string', 'text']:
            cond = '!=""'
        qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
    else:
        qry = '%s.%s.id>0' % tuple(request.args[:2])
    return qry
